const express = require('express');
const router = express.Router();
const sys_depart = require('../../../models/sys_depart')
const { generate19DigitId } = require('../../../utils/idUtils');


router.post('/sys/depart/paging', async (req, res) => {
    try {
        const { current = 1, size = 10 } = req.body
        const { deptName } = req.body.params

        // 获取部门数据
        let allDeparts;
        if (deptName && deptName.trim() !== '') {
            // 如果提供了部门名称，进行模糊搜索
            allDeparts = await sys_depart.findByDeptName(deptName.trim())
        } else {
            // 否则获取所有部门
            allDeparts = await sys_depart.findAll()
        }

        // 构建树形结构
        const buildTree = (parentId = '0') => {
            const children = allDeparts.filter(depart => depart.parent_id === parentId)
            return children.map(depart => ({
                id: depart.id,
                deptType: depart.dept_type,
                parentId: depart.parent_id,
                deptName: depart.dept_name,
                deptCode: depart.dept_code,
                sort: depart.sort,
                children: buildTree(depart.id)
            }))
        }

        const treeData = buildTree()

        // 实现分页逻辑
        const startIndex = (current - 1) * size
        const endIndex = startIndex + size
        let paginatedRecords = treeData.slice(startIndex, endIndex)



        // 计算总页数
        const total = treeData.length
        const pages = Math.ceil(total / size)

        return res.json({
            "msg": "操作成功！",
            "code": 0,
            "data": {
                "records": paginatedRecords,
                "total": total,
                "size": size,
                "current": current,
                "orders": [],
                "optimizeCountSql": true,
                "hitCount": false,
                "searchCount": true,
                "pages": pages
            },
            "success": true
        })
    } catch (error) {
        console.error(error);
        return res.status(500).json({
            "msg": "服务器内部错误",
            "code": 500,
            "success": false
        });
    }
})


router.post('/sys/depart/tree', async (req, res) => {
    try {
        // 获取所有部门数据
        const allDeparts = await sys_depart.findAll()

        // 构建树形结构的递归函数
        const buildTree = (parentId = '0') => {
            // 查找当前父级的所有子部门
            const children = allDeparts.filter(depart => depart.parent_id === parentId)

            // 按sort字段排序
            children.sort((a, b) => a.sort - b.sort)

            // 递归构建子树
            return children.map(depart => ({
                id: depart.id,
                deptType: depart.dept_type,
                parentId: depart.parent_id,
                deptName: depart.dept_name,
                deptCode: depart.dept_code,
                sort: depart.sort,
                children: buildTree(depart.id)
            }))
        }

        // 构建完整的树形结构
        const treeData = buildTree()

        return res.json({
            "msg": "操作成功！",
            "code": 0,
            "data": treeData,
            "success": true
        })
    } catch (error) {
        console.error('部门树形接口错误:', error);
        return res.status(500).json({
            "msg": "服务器内部错误",
            "code": 500,
            "success": false
        });
    }
})


router.post('/sys/depart/save', async (req, res) => {
    try {
        const { parentId, deptName, deptCode, deptType, id, sort } = req.body

        // 查询父部门
        const parentDepart = parentId == 0 ? await sys_depart.findByParentId(parentId) : await sys_depart.findById(parentId)

        // 查询该父节点的所有子节点
        const childDeparts = await sys_depart.findByParentId(parentId)

        // 生成部门编码：父部门编码 + 'A' + 序号（两位数字）
        const dept_code = parentId == 0 ? 'A' + (parentDepart.length + 1).toString().padStart(2, '0') : parentDepart[0].dept_code + 'A' + (childDeparts.length + 1).toString().padStart(2, '0')

        const depart = {
            id: generate19DigitId(),
            dept_type: 1,
            parent_id: parentId,
            dept_name: deptName,
            dept_code: dept_code, // 父节点是A01,子节点应该是A01A01,A01A02,A01A03依次递增
            sort: childDeparts.length + 1 // 子节点的顺序，从一开始
        }

        if (id) {
            // 更新部门名称
            await sys_depart.updateName(id, deptName)
        } else {
            // 新增部门
            await sys_depart.add(depart)
        }

        return res.json({
            "msg": "部门创建成功！",
            "code": 0,
            "success": true
        })
    } catch (error) {
        console.error('部门保存接口错误:', error);
        return res.status(500).json({
            "msg": "服务器内部错误",
            "code": 500,
            "success": false
        })
    }
})


router.post('/sys/depart/delete', async (req, res) => {
    try {
        const { ids } = req.body

        for (const id of ids) {
            //删除子部门
            await sys_depart.deleteById(id)
        }
        return res.json({ "msg": "请求成功！", "code": 0, "success": true })
    } catch (error) {
        console.error(error);
        return res.status(500).json({
            "msg": "服务器内部错误",
            "code": 500,
            "success": false
        })
    }
})

router.post('/sys/depart/detail', async (req, res) => {
    try {
        const { id } = req.body

        //查询部门详情
        const depart = await sys_depart.findById(id)

        const departDetail = depart.map(item => ({
            "id": item.id,
            "deptType": item.dept_type,
            "parentId": item.parent_id,
            "deptName": item.dept_name,
            "deptCode": item.dept_code,
            "sort": item.sort
        }))

        return res.json({
            "msg": "操作成功！",
            "code": 0,
            "data": departDetail[0],
            "success": true
        })
    } catch (error) {
        console.error(error);
        return res.status(500).json({
            "msg": "服务器内部错误",
            "code": 500,
            "success": false
        });
    }
})

async function generateDeptCode(parentId) {
    // 查询父部门
    let parentDepart;
    if (parentId === '0') {
        // 根部门：A01, A02, A03...
        parentDepart = await sys_depart.findByParentId(parentId)
    } else {
        // 子部门：基于父部门编码生成
        parentDepart = await sys_depart.findById(parentId)
    }

    // 查询该父节点的所有子节点
    const childDeparts = await sys_depart.findByParentId(parentId)

    // 动态生成部门编码
    let dept_code;
    if (parentId === '0') {
        // 根部门：A01, A02, A03...
        dept_code = 'A' + (parentDepart.length + 1).toString().padStart(2, '0')
        return dept_code
    } else {
        // 子部门：基于父部门编码生成
        const parentCode = parentDepart[0].dept_code;

        // 分析父部门编码的结构
        // 例如：A01, A01A01, A01A01A01 等
        const codeParts = parentCode.split('A').filter(part => part !== '');

        // 生成新的部门编码
        if (codeParts.length === 1) {
            // 一级子部门：A01 → A01A01, A01A02...
            dept_code = parentCode + 'A' + (childDeparts.length + 1).toString().padStart(2, '0')
            return dept_code
        } else {
            // 多级子部门：A01A01 → A01A01A01, A01A01A02...
            // 或者 A01A01A01 → A01A01A01A01, A01A01A01A02...
            const baseCode = parentCode;
            dept_code = baseCode + 'A' + (childDeparts.length + 1).toString().padStart(2, '0')
            return dept_code
        }
    }
}

router.post('/sys/depart/sort', async (req, res) => {
    try {
        const { id, sort } = req.body

        //调整选中id节点的结构，0 向上调整，1 向下调整

        // 查询该子节点
        const childDeparts = await sys_depart.findById(id)

        //查询选中节点的父节点
        const parentDepart = await sys_depart.findById(childDeparts[0].parent_id)

        // 调整排序
        if (sort == 0) {
            // 向上调整
            await sys_depart.updateParentId(id, parentDepart[0].parent_id)

            const deptCode = await generateDeptCode(parentDepart[0].id)
            await sys_depart.updateDeptCode(id, deptCode)

            // 调整子节点的排序
            await sys_depart.updateSort(id, parentDepart[0].sort + 1)
        } else {
            // 向下调整
            //await sys_depart.updateParentId(id, childDeparts[0].id)

            const deptCode = await generateDeptCode(childDeparts[0].id)
            console.log('deptCode', deptCode)
            //await sys_depart.updateDeptCode(id, deptCode)

            // 调整子节点的排序
            // await sys_depart.updateSort(id, childDeparts[0].sort - 1)
        }
        return res.json({ "msg": "请求成功！", "code": 0, "success": true })
    } catch (error) {
        console.error(error);
        return res.status(500).json({
            "msg": "服务器内部错误",
            "code": 500,
            "success": false
        })
    }
})

module.exports = router